package com.example.javabasic.thread.classtwo.countdown.demo1;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

// 等所有线程执行完成
public class CountDown {

    private static final Random random = new Random(System.currentTimeMillis());
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(10);
        //第一阶段 多线程处理任务
        System.out.println("-----------------开始多线程任务-----------------");
        IntStream.rangeClosed(0,10).forEach(i->{
            new Thread(()->{
                int i1 = random.nextInt(1000);
                System.out.println(Thread.currentThread().getName()+"执行任务时间"+i1);
                try {
                    Thread.sleep(i1);
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        });
        //第二阶段 等所有线程处理完  执行任务
        latch.await();
        System.out.println("----------------线程执行完成------------------");
    }
}
